import 'dart:convert';

import 'package:get/get.dart';
import 'package:play_lab/constants/my_strings.dart';
import 'package:play_lab/core/helper/string_format_helper.dart';
import 'package:play_lab/data/model/authorization/authorization_response_model.dart';
import 'package:play_lab/data/model/global/response_model/response_model.dart';
import 'package:play_lab/data/model/live_tv/live_tv_comments_response_model.dart';
import 'package:play_lab/data/repo/event/event_repo.dart';
import 'package:play_lab/data/services/ws_service.dart';
import 'package:play_lab/view/components/show_custom_snackbar.dart';

class TournamentLiveChatController extends GetxController {
  TournamentRepo repo;
  TournamentLiveChatController({required this.repo});
  List<LiveChatCommentModel> liveTournamentCommentList = [];
  WsSocketService wsSocketService = WsSocketService();

  void initWsSocketService(String id) {
    printX("======LIVE CHAT ===========");
    // if (wsSocketService.isConnected) {
    //   wsSocketService.disconnect();
    // }
    getCommentList(id);
    // wsSocketService.connect(id);
  }

  bool isLoading = false;
  Future<void> getCommentList(String tvId) async {
    isLoading = true;
    update();
    try {
      ResponseModel responseModel = await repo.getTournamentCommentList(tvId);
      if (responseModel.statusCode == 200) {
        printX(responseModel.responseJson);

        LiveTvChatResponseModel model = liveTvChatResponseModelFromJson(responseModel.responseJson);
        if (model.status == "success") {
          liveTournamentCommentList = model.data?.comments ?? [];
          update();
        } else {
          CustomSnackbar.showCustomSnackbar(errorList: model.message?.error ?? [MyStrings.somethingWentWrong], msg: [], isError: true);
        }
      } else {
        CustomSnackbar.showCustomSnackbar(errorList: [responseModel.message], msg: [], isError: true);
      }
    } catch (e) {
      printX(e);
    } finally {}
    isLoading = false;
    update();
  }

  //
  bool isSubmitLoading = false;
  Future<void> submitComment({
    required String id,
    required String comment,
  }) async {
    isSubmitLoading = true;
    update();
    try {
      ResponseModel responseModel = await repo.submitComment(id: id, comments: comment);
      if (responseModel.statusCode == 200) {
        AuthorizationResponseModel model = AuthorizationResponseModel.fromJson(jsonDecode(responseModel.responseJson));
        if (model.status == "success") {
          getCommentList(id);
          printX("New Comment Submitted :) now update list");
        } else {
          CustomSnackbar.showCustomSnackbar(errorList: model.message?.error ?? [MyStrings.somethingWentWrong], msg: [], isError: true);
        }
      } else {
        CustomSnackbar.showCustomSnackbar(errorList: [responseModel.message], msg: [], isError: true);
      }
    } catch (e) {
      printX(e.toString());
    }
    isSubmitLoading = false;
    update();
  }
}
